import os
from pathlib import Path

import click
from flask.cli import with_appcontext

IMAGE_INFO = Path(__file__).parent / "lib/image.txt"


class CreateImageError(Exception):
    """生成镜像失败"""


class DownloadImageError(Exception):
    """下载镜像失败"""


def download_image():
    """
    根据镜像文件下载镜像
    """
    os.system(". /root/adminrc.sh")
    with open(IMAGE_INFO, encoding="utf-8") as f:
        for info in f:
            try:
                image_name, image_id = info.split(":")
                print("download image:", image_name)
                os.system(f"glance image-download --file {image_name} {image_id}")
            except DownloadImageError as e:
                print(f"download image --{image_name} failed: {e}")
                continue


def create_image():
    """
    根据镜像名创建镜像
    """
    os.system(". /root/adminrc.sh")
    with open(IMAGE_INFO, encoding="utf-8") as f:
        for info in f:
            try:
                file_name = info.split(":")[0]
                if file_name == "0_核电MIS_mis_4-4-80_192.168.2.100":
                    os.system(
                        'glance image-create --name "0_核电MIS_mis_4-4-80_192.168.2.100" --file [成都]_核电MIS_mis_4-4-80_192.168.2.100 --disk-format qcow2 --container-format bare --visibility=public --property hw_video_model=qxl --property hw_firmware_type=uefi --property hw_vif_model=e1000 --property hw_disk_bus=ide'  # noqa
                    )
                else:
                    os.system(
                        'glance image-create --name "%s" --file %s --disk-format qcow2 --container-format bare --visibility=public --property hw_video_model=qxl --property hw_vif_model=e1000 --property hw_disk_bus=ide'  # noqa
                        % (file_name, file_name)
                    )
            except CreateImageError as e:
                print(f"create image --{file_name} failed: {e}")
                continue


@click.command("operate_image")
@click.option(
    "-o",
    "--operate",
    required=True,
    type=click.Choice(["create", "download"]),
    help="Syntax: python3 operate_image.py download|create",
)
@with_appcontext
def operate_image(operate):
    """操作虚拟机镜像"""

    if operate == "download":
        download_image()
    elif operate == "create":
        create_image()
